package kr.hkit.androidcomplete03.ch28_1;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import kr.hkit.androidcomplete03.R;
import kr.hkit.androidcomplete03.ch28_1.common.Item;
import kr.hkit.androidcomplete03.ch28_1.common.MyAdapter;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;



public class DomParser extends Activity {
	ListView list;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		list = (ListView) findViewById(R.id.orderListView);
		new ParsingXml().execute("order.xml");
	}
	
	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>>{
		ProgressDialog progressDlg;
		
		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(DomParser.this, "Wait", "Xml Parsing...");
		}
		
		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str=null;
			BufferedReader br=null;
			try {
				br = new BufferedReader(new InputStreamReader(openFileInput(params[0])));
				while( (str=br.readLine()) != null){
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {br.close();} catch (IOException e) {}
			}
			return parsingXml(sb.toString());
		}
		
		private ArrayList<Item> parsingXml(String xml) {
			Log.d("XML Parsing", xml);
			ArrayList<Item> list = new ArrayList<>();
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			try {
				DocumentBuilder builder = factory.newDocumentBuilder();
				InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
				Document doc = builder.parse(is);
				
				Element order =doc.getDocumentElement();//<order>
				NodeList items = order.getElementsByTagName("item");
				
				//<order>하위 item 태그노드 방문
				for(int i=0; i<items.getLength(); i++){
					Item subItem = new Item();
					Node node = items.item(i);
					//<item Price="23000" Maker="Samsung">Mouse</item>
					Node valueNode = node.getFirstChild();//Mouse Node
					subItem.setItemName(valueNode.getNodeValue()); //"Mouse"
					
					
					NamedNodeMap attrs = node.getAttributes();
					//<item Price="23000" Maker="Samsung"> 속성 순회
					for(int j=0; j<attrs.getLength();j++){
						Node attr = attrs.item(j);//Price="2300" or Maker="Samsung"
						if (attr.getNodeName().equalsIgnoreCase("price")){
							subItem.setItemPrice(Integer.parseInt(attr.getNodeValue()));
						}else{
							subItem.setItemMaker(attr.getNodeValue());
						}
					}
					
					list.add(subItem);
				}
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return list;
		}

		protected void onPostExecute(ArrayList<Item> result) {
			progressDlg.dismiss();
			MyAdapter adapter = new MyAdapter(DomParser.this, result);
			list.setAdapter(adapter);
		}
		
	}
}